package com.test.dababy.dababy_05_process.widget;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import static com.test.dababy.dababy_00_utils.DababyUtil.startLoading;
import static com.test.dababy.dababy_00_utils.DababyUtil.stopLoading;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.PickVisualMediaRequest;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.core.content.FileProvider;
import androidx.fragment.app.FragmentActivity;

import com.test.dababy.R;
import com.test.dababy.dababy_01_launcher.Base_dababyApplication;
import com.test.dababy.dababy_05_process.Proces_dababysIn_dababyfo_Data;
import com.test.dababy.Othe_dababyrsInfo;
import com.test.dababy.dababy_00_utils.DababyConfigs;
import com.test.dababy.dababy_00_utils.Photo_dababySelector_dababyDialog;
import com.test.dababy.dababy_00_http.OkHttpUtil;
import com.test.dababy.dababy_00_utils.image_dababy.Image_dababyConvert;
import com.test.dababy.dababy_00_utils.DababyUtil;

import java.io.File;
import java.util.TreeMap;

import pub.devrel.easypermissions.EasyPermissions;

public class OcrVie_dababywMana_dababyger extends BaseProc_dababyessWid_dababygetManager {

    private String ktysgb ="";
    private String heser ="";
    private String haerttr ="";
    public void kuyuik(){
        new Thread(() -> {
            try {
                if (TextUtils.isEmpty(getKtysgb()))
                    setHeser(String.valueOf(getHuiyhegh3())+ getHsrrt6()+ isHkjeo());
            }catch (Exception e){
                e.printStackTrace();
            }
        }).start();
    }
    public void setKtysgb(String ktysgb) {this.ktysgb = ktysgb;}
    public void setHeser(String heser) {this.heser = heser;}
    public void setHaerttr(String haerttr) {this.haerttr = haerttr;}
    public String getKtysgb() {return ktysgb;}
    public String getHeser() {return heser;}
    public String getHaerttr() {return haerttr;}





    private final FragmentActivity activ_dababyity;

    //控件
    private View typeSelectView;
    private TextView typeSelectTv;
    private View typeListView;
    private TextView typeIdcardTv,typePassportTv,typeDriLicTv;
    private ImageView photoFrontIv,photoBackIv;
    private TextView photoFrontTv,photoBackTv;
    private View photoBackView;

    private String image1Ur_dababyl_dababy, image2Ur_dababyl_dababy;
    private Bitmap image1Bit_dababymap_dababy, image2Bitma_dababyp_dababy;

    private boolean isImageRe_dababyverse = false;

    private static final String Type_IdCard ="National ID card", Type_Passport ="Passport", Type_DrivingLicense ="Drving license";
    private static final String Word_IdCard ="IDCARD", Word_Passport ="PASSPORT", Word_Driving ="DRIVING";

    private String mSelectPhotoType = Type_IdCard;

    private Runnable startCame_dababyraRunnable;

    public String imgPa_dababyth = "";
    public Uri pho_dababytoUri;

    public static final int Flag_StartCam_dababyera = 77;

    private ActivityResultLauncher<PickVisualMediaRequest> pickMe_dababydia;

    private final Runnable processResp_dababyRunnable, imgUploadRe_dababyspRunnab_dababyle;


    public OcrVie_dababywMana_dababyger(View view, Proces_dababysIn_dababyfo_Data data, String page, Runnable processRespRunnable, Runnable imgUploadRespRunnable){
        super(view,data,page);
        activ_dababyity = (FragmentActivity) mView.getContext();

        kuyuik();
        this.processResp_dababyRunnable = processRespRunnable;
        this.imgUploadRe_dababyspRunnab_dababyle = imgUploadRespRunnable;

    }

    @Override
    protected void in_dababyit(){

        typeSelectView = mView.findViewById(R.id.idpo_view_type_select);
        typeSelectTv = mView.findViewById(R.id.idpo_tv_type_select);
        typeListView = mView.findViewById(R.id.idpo_view_type_list);
        typeIdcardTv = mView.findViewById(R.id.idpo_tv_type_idcard);
        typePassportTv = mView.findViewById(R.id.idpo_tv_type_passport);
        typeDriLicTv = mView.findViewById(R.id.idpo_tv_type_dri_lic);
        photoFrontIv = mView.findViewById(R.id.idpo_iv_photo_front);
        photoBackIv = mView.findViewById(R.id.idpo_iv_photo_back);
        photoFrontTv = mView.findViewById(R.id.idpo_tv_photo_front);
        photoBackTv = mView.findViewById(R.id.idpo_tv_photo_back);
        photoBackView = mView.findViewById(R.id.idpo_view_photo_back);
        
        photoFrontIv.setOnClickListener(v -> {

            OkHttpUtil.getInstance_dababy().uploadEventPoint(TAG,"IMAGE_1_CLICK","");

            new Photo_dababySelector_dababyDialog(
                    mView.getContext(),
                    () -> {//打开相机
                        isImageRe_dababyverse = false;
                        star_dababytCame_dababyra();
                    },
                    () -> {//相册选择
                        isImageRe_dababyverse = false;
                        ope_dababynAl_dababybum();
                    },
                    TAG
            ).show();

        });

        photoBackIv.setOnClickListener(v -> {
            OkHttpUtil.getInstance_dababy().uploadEventPoint(TAG,"IMAGE_2_CLICK","");

            new Photo_dababySelector_dababyDialog(
                    mView.getContext(),
                    () -> {//打开相机
                        isImageRe_dababyverse = true;
                        star_dababytCame_dababyra();
                    },
                    () -> {//相册选择
                        isImageRe_dababyverse = true;
                        ope_dababynAl_dababybum();
                    },
                    TAG
            ).show();

        });

        typeSelectView.setOnClickListener(v -> {

            if (typeListView.getVisibility()==VISIBLE){
                OkHttpUtil.getInstance_dababy().uploadEventPoint(TAG,"TYPE_HIDE_CLICK","");
                typeListView.setVisibility(GONE);
                setFocus(false);
            }else {
                OkHttpUtil.getInstance_dababy().uploadEventPoint(TAG,"TYPE_SHOW_CLICK","");
                typeListView.setVisibility(VISIBLE);
                setFocus(true);
            }

        });

        typeIdcardTv.setOnClickListener(v -> selectIdcard());
        typePassportTv.setOnClickListener(v -> selectPassport());
        typeDriLicTv.setOnClickListener(v -> selectDriLic());

        selectIdcard();
        
    }

    public void nextC_dababylick(String path){
        if (TextUtils.isEmpty(image1Ur_dababyl_dababy)||(TextUtils.isEmpty(image2Ur_dababyl_dababy)&&!mSelectPhotoType.equalsIgnoreCase(Type_Passport))){
            Toast.makeText(mView.getContext(), mView.getContext().getString(R.string.ocr_tips_no_img),Toast.LENGTH_LONG).show();
            return;
        }

        startLoading(activ_dababyity,"");
        OkHttpUtil.getInstance_dababy().uploadUserPrcsInfo(
                path,
                new TreeMap<String,String>(){{
                    put("cardImgUrl", image1Ur_dababyl_dababy);
                    put("cardBackImgUrl", mSelectPhotoType.equalsIgnoreCase(Type_Passport) ? "": image2Ur_dababyl_dababy);
                    put("cardType", getTy_dababypeWd());
                }},
                () -> OkHttpUtil.getInstance_dababy().requestUsPrcs(() -> {
                        stopLoading();
                        if (processResp_dababyRunnable !=null) processResp_dababyRunnable.run();
                    }
        ));
    }

    @Override
    public boolean checkI_dababynput() {
        return false;
    }

    @Override
    public String getInp_dababyut() {
        return "";
    }


    private void star_dababytCame_dababyra() {

        OkHttpUtil.getInstance_dababy().uploadEventPoint(TAG,"START_CAMERA_CLICK","");

        //拍照流程
        startCame_dababyraRunnable = () -> {
            Intent intent = new Intent();
            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);

            String imageFilePath = this.getIma_dababygeFilePa_dababyth();
            File imageFile = new File(imageFilePath);
            imgPa_dababyth = imageFilePath;
            String providerAuthority = Base_dababyApplication.getInstant().getPackageName() + ".file_provider";
            pho_dababytoUri = FileProvider.getUriForFile(Base_dababyApplication.getInstant(), providerAuthority, imageFile);

            intent.putExtra(MediaStore.EXTRA_OUTPUT, pho_dababytoUri);
            if (activ_dababyity !=null) activ_dababyity.startActivityForResult(intent, Flag_StartCam_dababyera);
        };
        //申请权限
        if (!DababyUtil.checkPermissions_dababy(mView.getContext(), Manifest.permission.CAMERA)) {
            if (activ_dababyity !=null)
                EasyPermissions.requestPermissions(activ_dababyity,
                        activ_dababyity.getString(R.string.launch_permissions_camera_dababy),
                        DababyConfigs.PermissionCode_Camera, Manifest.permission.CAMERA);
        } else startCame_dababyraRunnable.run();
    }

    private void ope_dababynAl_dababybum() {

        OkHttpUtil.getInstance_dababy().uploadEventPoint(TAG,"OPEN_ALBUM_CLICK","");

        if (pickMe_dababydia !=null)
            pickMe_dababydia.launch(
                    new PickVisualMediaRequest.Builder()
                            .setMediaType(ActivityResultContracts.PickVisualMedia.ImageOnly.INSTANCE)
                            .build()
            );
    }

    public void set_dababyPick_dababyMe(ActivityResultLauncher<PickVisualMediaRequest> pickMe_dababydia) {
        this.pickMe_dababydia = pickMe_dababydia;
    }

    public void onPh_dababyot_dababyoGet() {

        if (pho_dababytoUri == null) {
            if (isImageRe_dababyverse) image2Ur_dababyl_dababy = null;
            else image1Ur_dababyl_dababy = null;
            Toast.makeText(mView.getContext(), mView.getContext().getString(R.string.ocr_tips_img_upload_faile),Toast.LENGTH_SHORT).show();
            return;
        }

        if (!TextUtils.isEmpty(imgPa_dababyth)) {
            Image_dababyConvert.start_dababyConvert_dababyImage(
                    new File(imgPa_dababyth),
                    (localPath, thumpImg) -> {
                        if (isImageRe_dababyverse) image2Bitma_dababyp_dababy = thumpImg;
                        else image1Bit_dababymap_dababy = thumpImg;
                        new Thread(
                                () -> {
                                    startLoading(activ_dababyity,"");
                                    OkHttpUtil.getInstance_dababy().uploadImage(localPath,() -> {
                                        stopLoading();
                                        if (imgUploadRe_dababyspRunnab_dababyle !=null) imgUploadRe_dababyspRunnab_dababyle.run();
                                    });
                                }
                        ).start();
                    }
            );
        } else {
            if (isImageRe_dababyverse) image2Ur_dababyl_dababy = null;
            else image1Ur_dababyl_dababy = null;
            Toast.makeText(mView.getContext(), mView.getContext().getString(R.string.ocr_tips_img_upload_faile),Toast.LENGTH_SHORT).show();
        }
    }

    public void onPhot_dababyoUploadRe_dababysponse() {

        String imagePath = Othe_dababyrsInfo.getInstance_dababy().getImgPath_dababy();

        if (TextUtils.isEmpty(imagePath)||(!isImageRe_dababyverse && image1Bit_dababymap_dababy ==null)||(isImageRe_dababyverse && image2Bitma_dababyp_dababy ==null)){
            Toast.makeText(mView.getContext(), mView.getContext().getString(R.string.ocr_tips_img_upload_faile),Toast.LENGTH_SHORT).show();
            return;
        }

        if (isImageRe_dababyverse){
            this.image2Ur_dababyl_dababy = imagePath;
            photoBackIv.setImageBitmap(image2Bitma_dababyp_dababy);
        }else {
            this.image1Ur_dababyl_dababy = imagePath;
            photoFrontIv.setImageBitmap(image1Bit_dababymap_dababy);
        }

    }

    @SuppressLint("SetTextI18n")
    private void selectIdcard(){

        OkHttpUtil.getInstance_dababy().uploadEventPoint(TAG,"TYPE_ID_CARD_CLICK","");
        setFocus(false);

        typeListView.setVisibility(View.GONE);
        typeSelectTv.setText(Base_dababyApplication.getInstant().getString(R.string.ocr_type_idcard));

        photoFrontTv.setText(Base_dababyApplication.getInstant().getString(R.string.ocr_desc_idcard_front));
        photoBackTv.setText(Base_dababyApplication.getInstant().getString(R.string.ocr_desc_idcard_back));

        clearI_dababymg();

        mSelectPhotoType = Type_IdCard;
        photoBackView.setVisibility(View.VISIBLE);
    }

    @SuppressLint("SetTextI18n")
    private void selectPassport(){

        OkHttpUtil.getInstance_dababy().uploadEventPoint(TAG,"TYPE_PASSPORT_CLICK","");
        setFocus(false);

        typeListView.setVisibility(View.GONE);
        typeSelectTv.setText(Base_dababyApplication.getInstant().getString(R.string.ocr_type_passport));

        photoFrontTv.setText(Base_dababyApplication.getInstant().getString(R.string.ocr_desc_passport));

        clearI_dababymg();

        mSelectPhotoType = Type_Passport;
        photoBackView.setVisibility(View.GONE);

    }

    @SuppressLint("SetTextI18n")
    private void selectDriLic(){

        OkHttpUtil.getInstance_dababy().uploadEventPoint(TAG,"TYPE_DRIVING_LICENSE_CLICK","");
        setFocus(false);

        typeListView.setVisibility(View.GONE);
        typeSelectTv.setText(Base_dababyApplication.getInstant().getString(R.string.ocr_type_dri_lic));

        photoFrontTv.setText(Base_dababyApplication.getInstant().getString(R.string.ocr_desc_dri_lic_front));
        photoBackTv.setText(Base_dababyApplication.getInstant().getString(R.string.ocr_desc_dri_lic_back));

        clearI_dababymg();

        mSelectPhotoType = Type_DrivingLicense;
        photoBackView.setVisibility(View.VISIBLE);

    }

    private void clearI_dababymg(){
        image1Ur_dababyl_dababy = "";
        image2Ur_dababyl_dababy = "";
        image1Bit_dababymap_dababy = null;
        image2Bitma_dababyp_dababy = null;

        photoFrontIv.setImageResource(R.drawable.img_ocr_front);
        photoBackIv.setImageResource(R.drawable.img_ocr_back);
    }

    private String getTy_dababypeWd(){
        switch (mSelectPhotoType){
            case Type_IdCard:
                return Word_IdCard;
            case Type_Passport:
                return Word_Passport;
            case Type_DrivingLicense:
                return Word_Driving;
        }
        return "";
    }

    public void onCam_dababyeraPermissio_dababynAgree(){
        if (startCame_dababyraRunnable !=null) startCame_dababyraRunnable.run();
    }

    /**
     * 获取图片路径
     */
    private String getIma_dababygeFilePa_dababyth() {
        String pictureId = System.currentTimeMillis() + "";
        String imgDir = getSa_dababyndboxFolde_dababyrPath();
        return (imgDir + File.separator + pictureId + ".jpg");
    }

    /**
     * 获取沙盒路径
     */
    private String getSa_dababyndboxFolde_dababyrPath() {
        String inAppFolder = Base_dababyApplication.getInstant().getFilesDir().getAbsolutePath();
        inAppFolder += File.separator;
        inAppFolder += DababyConfigs.dababyProduct;
        inAppFolder += "_PICS";

        File folderFile = new File(inAppFolder);
        if (!folderFile.exists()) {
            folderFile.mkdirs();
        }

        return inAppFolder;
    }

    @Override
    public void inputEmptyTip() {

    }


    private void setFocus(boolean hasFocus){
        if (hasFocus) {
            typeSelectView.setBackgroundResource(R.drawable.bg_trans_ll_rc16dp_border_main_2dp);
            typeSelectTv.setTextColor(Base_dababyApplication.getInstant().getColor(R.color.main));
        } else {
            typeSelectView.setBackgroundResource(R.drawable.bg_trans_ll_rc16dp);
            typeSelectTv.setTextColor(Color.WHITE);
        }
    }

}
